import { KV } from "./kv";
import { IRequest, Router, RouterOptions } from "itty-router";

export interface Args {
  ctx: ExecutionContext;
  kv: KV;
}

type TRequest = Request & Pick<IRequest, "params" | "query"> & { content: any };
type TResponse = Response | void;
export type RouteHandler = {
  (request: TRequest, args: Args): TResponse | Promise<TResponse>;
};
type RouteEntry = { 0: string; 1: RegExp; 2: RouteHandler[] };
type Route = { (path: string, ...handlers: RouteHandler[]): any };
type RouterType = {
  handle: (request: Request, args: Args) => Promise<Response>;
  routes: RouteEntry[];
  all: Route;
  options: Route;
  get: Route;
  post: Route;
  put: Route;
  patch: Route;
  delete: Route;
};

export function Router2(options?: RouterOptions) {
  return Router(options) as unknown as RouterType;
}

export function first(query: string | string[] | undefined) {
  return query instanceof Array ? query[0] : query;
}
